export async function draw(container, texture, format='rgb') {
  // Calling the regl module with no arguments creates a full screen canvas and
  // WebGL context, and then uses this context to initialize a new REGL instance
  const [height, width] = texture.shape;
  const imgData = await texture.data();
  texture = {
    width,
    height,
    data: new Uint8Array(imgData),
    format
  }
  const liItem = document.createElement('li');
  liItem.style.width = width + 'px';
  liItem.style.height = height + 'px';
  container.appendChild(liItem)
  const regl = require('regl')({
    container: liItem,
  });

  // Calling regl() creates a new partially evaluated draw command
  const drawTriangle = regl({
    // Shaders in regl are just strings.  You can use glslify or whatever you want
    // to define them.  No need to manually create shader objects.
    frag: `
    precision mediump float;
    varying vec2 uv;
    uniform sampler2D texture;
    void main() {
      gl_FragColor = texture2D(texture, uv);
    }`,

    vert: `
    precision mediump float;
    attribute vec2 position;
    varying vec2 uv;
    void main() {
      uv = (position+1.0)/2.0;

      gl_Position = vec4(position * vec2(1, -1), 0, 1);
    }`,

    // Here we define the vertex attributes for the above shader
    attributes: {
      // regl.buffer creates a new array buffer object
      position: regl.buffer([
        [-1, 1], // no need to flatten nested arrays, regl automatically
        [-1, -1], // unrolls them into a typedarray (default Float32)
        [1, -1],
        [1, -1],
        [1, 1],
        [-1, 1],
      ]),
      // regl automatically infers sane defaults for the vertex attribute pointers
    },

    uniforms: {
      // This defines the color of the triangle to be a dynamic variable
      texture: regl.texture(texture),
    },

    // This tells regl the number of vertices to draw in this command
    count: 6,
  });

  // regl.frame() wraps requestAnimationFrame and also handles viewport changes
  regl.frame(({ time }) => {
    // clear contents of the drawing buffer
    regl.clear({
      color: [0, 0, 0, 0],
      depth: 1,
    });

    // draw a triangle using the command defined above
    drawTriangle({
      color: [
        Math.cos(time * 0.001),
        Math.sin(time * 0.0008),
        Math.cos(time * 0.003),
        1,
      ],
    });
  });
}
